package be.bonamis.umpire.utils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import be.bonamis.umpire.domain.Club;
import be.bonamis.umpire.domain.GameType;
import be.bonamis.umpire.old.domain.XlsCaUmpire;
import be.bonamis.umpire.old.domain.XlsRanking;

public class FileUtils<T> {

	@SuppressWarnings("unchecked")
	public static <T> List<T> read(String inputFile) {

		InputStream in = FileUtils.class.getClassLoader().getResourceAsStream(inputFile);
		String[][] excelArray = null;
		List<T> list = new ArrayList<T>();
		try {
			excelArray = readFile(in);
			List<String> columName = new ArrayList<String>();
			for (int i = 0; i < excelArray[0].length; i++) {
				if (excelArray[0][i].length() > 0)
					columName.add(excelArray[0][i]);
			}
			T type = null;
			for (int i = 1; i < excelArray.length; i++) {
				if (!(excelArray[i][0].isEmpty())) {
					if (inputFile.startsWith("GameType")) {
						type = (T) new GameType();
					} else if (inputFile.startsWith("XlsCa")) {
						type = (T) new XlsCaUmpire();
					} else if (inputFile.startsWith("Rank")) {
						type = (T) new XlsRanking();
					} else if (inputFile.startsWith("Club")) {
						type = (T) new Club();
					}
					String methodName = "";
					int c = 0;
					for (String string : columName) {
						methodName = "set" + Character.toString(string.charAt(0)).toUpperCase()
								+ string.substring(1, string.length());
						Method method = type.getClass().getMethod(methodName, String.class);
						method.invoke(type, excelArray[i][c++]);
					}
					list.add(type);
				}

			}
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	public static String[][] readFile(InputStream is) {
		Workbook w = null;
		try {
			w = Workbook.getWorkbook(is);
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Sheet sheet = w.getSheet(0);
		String[][] st = new String[sheet.getRows()][sheet.getColumns()];
		for (int i = 0; i < sheet.getRows(); i++) {
			for (int j = 0; j < sheet.getColumns(); j++) {
				st[i][j] = sheet.getCell(j, i).getContents();
			}
		}
		return st;
	}

}
